package com.springboot.demo.controller;

import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.github.pagehelper.PageInfo;
import com.springboot.demo.annotation.LoginCheckAnnotation;
import com.springboot.demo.bean.Message;
import com.springboot.demo.common.CommonResult;
import com.springboot.demo.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author:linwenfeng
 * @Time:2020/10/23 10:06
 */
//@LoginCheckAnnotation
@RestController
public class Test1Controller {

    @Autowired
    MessageService messageService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    //    @LoginCheckAnnotation
    @RequestMapping("/test1")
    public CommonResult test1() {
        return CommonResult.success("1个测试");
    }


    @RequestMapping("/test2")
    public CommonResult test2() {
        return CommonResult.success("2个测试");
    }

    @LoginCheckAnnotation
    @RequestMapping("/test3")
    public CommonResult test3(HttpServletRequest request) {
//        String token = request.getHeader("token");
//        JWTUtil jwtUtil = new JWTUtil(token);
//        Date expireTime = jwtUtil.getExpireTime();
//        System.out.println(expireTime.getTime());
        return CommonResult.success("123", "abc");
    }

    @PostMapping("/getMsg")
    public CommonResult getMsg(
            @RequestParam(name = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            @RequestParam(name = "pageNum", defaultValue = "10", required = false) Integer pageSize
    ) {
        List<Message> messages = messageService.selectAll(pageNum, pageSize);
        PageInfo pageInfo = new PageInfo(messages);
        return CommonResult.success("查询所有", pageInfo);
    }

    //redis分布式锁demo
    @GetMapping("/redisTest")
    public String redisTest(){

            Integer goods = Integer.parseInt(stringRedisTemplate.opsForValue().get("goods"));
            String lockKey = "lock";
            String value = "thread" + UUID.randomUUID();
            Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, value, 10, TimeUnit.SECONDS);

            if (!aBoolean){
                return "error";
            }

            if (goods > 0){
                int realGoods = goods - 1;
                stringRedisTemplate.opsForValue().set("goods", realGoods + "");
                System.out.println("扣减库存成功,剩余库存: "+realGoods);
            } else {
                System.out.println("扣减库存失败");
            }

            String s = stringRedisTemplate.opsForValue().get(lockKey);

            if (s.equals(value)){
                stringRedisTemplate.delete(lockKey);
            }
        return "ok";
    }
}
